package exhi.action;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.stp.core.entity.IGridRowFactory;
import com.stp.core.entity.XGrid;
import com.stp.core.entity.XGridPage;
import com.stp.core.entity.XGridRow;
import com.stp.core.entity.XMsg;
import com.stp.core.util.DateUtil;
import com.stp.std.entity.AuditLog;
import com.stp.std.entity.ParamInfo;

import exhi.entity.EntpBexhi;
import exhi.entity.EntpUser;
import exhi.entity.ExhiCfg;
import exhi.manager.EntpBexhiMng;

@Controller
@RequestMapping("/entp")
public class EntpBookAct extends ViewExhiAct {

	private static final String MOD = "展会预约";

	// 场馆预约
	private static final String PATH_BOOK_DETAIL = "/book-detail";
	private static final String PATH_BOOK_SAVE = "/book-save";
	private static final String PATH_BOOK_VIEW = "/book-view";
	private static final String PATH_BOOK_SB = "/book-sb";

	// 项目预约
	private static final String PATH_BIG_DETAIL = "/book-big-detail";
	private static final String PATH_BIG_SAVE = "/book-big-save";
	private static final String PATH_BIG_VIEW = "/book-big-view";
	private static final String PATH_BIG_SB = "/book-big-sb";
	private static final String PATH_BIG_ZZSB = "/book-big-zzsb";

	private static final String PATH_TABLE = "/book-table";

	private static final String PATH_TABLE2 = "/book";

	private static final String PATH_BOOK = "/book-link";

	private static final String PATH_DELETE = "/book-delete";

	private static final String PATH_CHECK = "/book-check";
	private static final String PATH_CHECK_SAVE = "/book-check-save";

	// 场馆预约
	private static final String PATH_LIST = "/book-list";

	// 场馆预约确认
	private static final String PATH_CHECK_LIST = "/check-book-list";

	// 场馆合同确认
	private static final String PATH_AGREE_LIST = "/agree-book-list";

	private String code = "";

	// 大型国际展场馆预约
	@RequestMapping(PATH_BOOK)
	public void book(ModelMap model) {

	}

	// 大型国际展场馆预约
	@RequestMapping(PATH_TABLE2)
	public void table2(ModelMap model) {
		List<ParamInfo> lstStatus = paramMng.findByProperty("type", "entpStep",
				"sort ");
		model.addAttribute("lstStatus", lstStatus);
	}

	// 大型国际展场馆预约
	@RequestMapping(PATH_TABLE)
	public void table(
			@RequestParam(value = "code", required = true, defaultValue = "") String code,
			ModelMap model) {
		model.addAttribute("code", code);

		// 场馆预约
		if (code.equalsIgnoreCase("01")) {
			List<ParamInfo> lstStatus = paramMng.findByProperty("type",
					"entpStep", "sort ");
			model.addAttribute("url", PATH_LIST.substring(1) + ".jspx");
			model.addAttribute("lstStatus", lstStatus);
		}

		// 场馆合同确认
		if (code.equalsIgnoreCase("05")) {
			model.addAttribute("url", PATH_CHECK_LIST.substring(1) + ".jspx");
		}

		// 合同预约确认
		if (code.equalsIgnoreCase("60")) {
			model.addAttribute("url", PATH_AGREE_LIST.substring(1) + ".jspx");
		}
	}

	// 权限json数据
	@RequestMapping(PATH_LIST)
	@ResponseBody
	public String infoList(XGridPage page, @RequestParam("code") String code,
			@RequestParam("cap_code") String capCode,
			@RequestParam("cap_name") String capName)
			throws InstantiationException, IllegalAccessException {
		this.code = code;
		String uid = getEntpUser().getUid();
		String sql = "from EntpBexhi info where info.uid='" + uid + "'";
		sql += sqlModel
				.getSQLChars("info.zlhmc", "like", capName, false, "and");
		sql += sqlModel.getSQLChars("info.status", "=", capCode, false, "and");
		sql += " order by info.createtime desc";
		InfoGridRow row = new EntpBookAct.InfoGridRow();
		XGrid grid = entpBexhiMng.getXGrid(sql, row, page.getPageNo(),
				page.getPageSize(), false);
		if (null == grid)
			return "";
		return "{\"xGrid\":" + toJson(grid) + "}";
	}

	class InfoGridRow implements IGridRowFactory {
		public XGridRow builderXRow(Object obj) {
			// TODO Auto-generated method stub
			XGridRow xrow = null;
			String s = "";
			List<ParamInfo> lst;
			String sql;
			DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
			if (obj instanceof EntpBexhi) {
				xrow = new XGridRow();
				EntpBexhi info = (EntpBexhi) obj;
				xrow.setId(info.getId());
				List t = new ArrayList();
				t.add("");
				t.add("大型国际展");
				if (null != info.getCreatetime())
					t.add(df1.format(info.getCreatetime()));
				else
					t.add("");
				t.add(info.getZlhmc());
				// 状态
				sql = "from ParamInfo info where info.type='entpStep' and info.pCode='"
						+ info.getStatus() + "'";
				lst = paramMng.list(sql);
				for (ParamInfo p : lst) {
					t.add(p.getpName());
				}
				t.add(getBookUrl(info.getId(), info.getStatus()));
				xrow.setData(t);
			}
			return xrow;
		}
	}

	// 权限json数据
	@RequestMapping(PATH_CHECK_LIST)
	@ResponseBody
	public String infoCheckList(XGridPage page,
			@RequestParam("code") String code,
			@RequestParam("cap_code") String capCode,
			@RequestParam("cap_name") String capName)
			throws InstantiationException, IllegalAccessException {
		this.code = code;
		// String uid = getEntpUser().getUid();
		/*
		 * String sql =
		 * "from EntpBexhi info where info.status='05' and info.uid='" + uid +
		 * "'";
		 */
		String sql = "from EntpBexhi info where info.status not in ('01') ";
		sql += sqlModel
				.getSQLChars("info.zlhmc", "like", capName, false, "and");
		if ("03".equalsIgnoreCase(capCode) || "05".equalsIgnoreCase(capCode))
			sql += sqlModel.getSQLChars("info.status", "=", capCode, false,
					"and");
		if ("10".equalsIgnoreCase(capCode)) {
			sql += sqlModel
					.getSQLChars("info.status", "<>", "03", false, "and");
			sql += sqlModel
					.getSQLChars("info.status", "<>", "05", false, "and");
		}
		sql += " order by info.createtime desc";
		CheckGridRow row = new EntpBookAct.CheckGridRow();
		XGrid grid = entpBexhiMng.getXGrid(sql, row, page.getPageNo(),
				page.getPageSize(), false);
		if (null == grid)
			return "";
		return "{\"xGrid\":" + toJson(grid) + "}";
	}

	class CheckGridRow implements IGridRowFactory {
		public XGridRow builderXRow(Object obj) {
			// TODO Auto-generated method stub
			XGridRow xrow = null;
			String s = "";
			EntpUser u;
			DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
			if (obj instanceof EntpBexhi) {
				xrow = new XGridRow();
				EntpBexhi info = (EntpBexhi) obj;
				xrow.setId(info.getId());
				List t = new ArrayList();
				t.add("");
				t.add("大型国际展");
				if (null != info.getCreatetime())
					t.add(df1.format(info.getCreatetime()));
				else
					t.add("");
				t.add(info.getZlhmc());
				// 状态
				if ("05".equalsIgnoreCase(info.getStatus())) {
					t.add("待确认");
				} else {
					if ("03".equalsIgnoreCase(info.getStatus())) {
						t.add("已退回");
					} else {
						t.add("已确认");
					}
				}
				t.add(getBookUrl(info.getId(), info.getStatus()));
				xrow.setData(t);
			}
			return xrow;
		}
	}

	// 权限json数据
	@RequestMapping(PATH_AGREE_LIST)
	@ResponseBody
	public String infoAgreeList(XGridPage page,
			@RequestParam(value = "code") String code,
			@RequestParam("cap_code") String capCode,
			@RequestParam("cap_name") String capName)
			throws InstantiationException, IllegalAccessException {
		// String uid = getEntpUser().getUid();
		// String sql =
		// "from EntpBexhi info where info.status>='30' and info.uid='"
		// + uid + "'";
		String sql = "from EntpBexhi info where info.status  in ('60','70','80','90') ";
		sql += sqlModel
				.getSQLChars("info.zlhmc", "like", capName, false, "and");
		if ("60".equalsIgnoreCase(capCode)) {
			sql += sqlModel.getSQLChars("info.status", "=", capCode, false,
					"and");
		}
		if ("70".equalsIgnoreCase(capCode)) {
			sql += sqlModel.getSQLChars("info.status", "<>", capCode, false,
					"and");
		}
		sql += " order by info.createtime desc";
		this.code = code;
		AgreeGridRow row = new EntpBookAct.AgreeGridRow();
		XGrid grid = entpBexhiMng.getXGrid(sql, row, page.getPageNo(),
				page.getPageSize(), false);
		if (null == grid)
			return "";
		return "{\"xGrid\":" + toJson(grid) + "}";
	}

	class AgreeGridRow implements IGridRowFactory {
		public XGridRow builderXRow(Object obj) {
			// TODO Auto-generated method stub
			XGridRow xrow = null;
			String s = "";
			EntpUser u = null;
			DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
			if (obj instanceof EntpBexhi) {
				xrow = new XGridRow();
				EntpBexhi info = (EntpBexhi) obj;
				xrow.setId(info.getId());
				List t = new ArrayList();
				if (info.getUid() != null) {
					u = entpMng.get(info.getUid());
					if (u != null)
						t.add(u.getMc());
					else
						t.add("");
				} else {
					t.add("");
				}
				t.add("大型国际展");
				if (null != info.getCreatetime())
					t.add(df1.format(info.getCreatetime()));
				else
					t.add("");
				t.add(info.getZlhmc());
				// 状态
				if ("60".equalsIgnoreCase(info.getStatus())) {
					t.add("待确认");
				} else {
					t.add("已确认");
				}
				t.add(getBookUrl(info.getId(), info.getStatus()));
				xrow.setData(t);
			}
			return xrow;
		}
	}

	// 数据保存
	@RequestMapping(PATH_BOOK_SAVE)
	public String bookSave(@RequestParam("projectId") String projectId,
			@RequestParam("code") String code,
			@ModelAttribute("entpBexhi") EntpBexhi entpBexhiInfo, ModelMap model) {
		if (entpBexhiInfo.getId() == null) {
			String sql = " from EntpBexhi where token='" + projectId + "'";
			List<EntpBexhi> lst = entpBexhiMng.list(sql);
			if (lst.size() == 0) {
				entpBexhiInfo.setCreatetime(new Date());
				entpBexhiInfo.setStatus("01");
				entpBexhiInfo.setUid(getEntpUser().getUid());
				entpBexhiInfo.setToken(projectId);
				entpBexhiMng.save(entpBexhiInfo);
				String entpId = entpBexhiInfo.getId();
				if (projectId == null || !entpId.equalsIgnoreCase(projectId)) {
					relationMng.saveEntpRelation(projectId, entpId, "ZB");// 主办单位
					relationMng.saveEntpRelation(projectId, entpId, "CB");// 承办单位
					relationMng.saveEntpRelation(projectId, entpId, "ZC");// 支持单位
					relationMng.saveEntpRelation(projectId, entpId, "XB");// 协办单位
					relationMng.saveEntpRelation(projectId, entpId, "QT");// 其他单位
					relationMng.saveEntpRelation(projectId, entpId, "exhiType");// 展会类型
					relationMng.saveEntpRelation(projectId, entpId, "zldd");// 展会场馆
					sql = "update t_entp_book set yybh=seq('"
							+ entpBexhiInfo.getYear()
							+ "','book')  where bid='" + entpBexhiInfo.getId()
							+ "'";
					entpBexhiMng.query(sql);
				}
			}
		} else {
			entpBexhiMng.update(entpBexhiInfo);
		}
		log("预约审核", " 已保存场馆预约申请", entpBexhiInfo.getId(), null);
		return "redirect:" + PATH_BOOK_VIEW.substring(1) + ".jspx?code=" + code
				+ "&infoId=" + entpBexhiInfo.getId();
	}

	// 明细数据
	@RequestMapping(PATH_BIG_DETAIL)
	public void bookBigDetail(@RequestParam("code") String code,
			@ModelAttribute("entpBexhi") EntpBexhi entpBexhi, ModelMap model) {
		model.addAttribute("code", code);
		showBexhiView(entpBexhi, model);
	}

	// 明细数据
	@RequestMapping(PATH_BOOK_VIEW)
	public void bookView(@RequestParam("code") String code,
			@ModelAttribute("entpBexhi") EntpBexhi entpBexhi, ModelMap model) {
		model.addAttribute("code", code);
		showBexhiView(entpBexhi, model);
	}

	@RequestMapping(PATH_BOOK_SB)
	@ResponseBody
	public String bookSB(@ModelAttribute("entpBexhi") EntpBexhi entpBexhi,
			ModelMap model) {
		AuditLog audit = new AuditLog();
		if ("01".equalsIgnoreCase(entpBexhi.getStatus())
				|| "03".equalsIgnoreCase(entpBexhi.getStatus())) {
			entpBexhi.setStatus("05"); // 申报到场馆确认
			entpBexhiMng.update(entpBexhi);
			audit.setAuditGroup("B");
			audit.setAuditId(entpBexhi.getId());
			audit.setAuditTitle("已提交大型展场馆预约");
			audit.setAuditSendId("05");
			audit.setAuditTime(new Date());
			if (null != getEntpUser())
				audit.setAuditName(getEntpUser().getMc());
			audit.setAuditStatus("T");
			auditLogMng.save(audit);
			log("预约审核", " 已提交场馆预约申请", entpBexhi.getId(), null);
		}
		XMsg msg = new XMsg();
		msg.setState(true);
		return toJson(msg);
	}

	@RequestMapping(PATH_BIG_ZZSB)
	@ResponseBody
	public String bookZZSB(@ModelAttribute("entpBexhi") EntpBexhi entpBexhi,
			ModelMap model) {
		if ("10".equalsIgnoreCase(entpBexhi.getStatus())
				|| "25".equalsIgnoreCase(entpBexhi.getStatus())) {
			entpBexhi.setStatus("20"); // 申报到场馆确认
			entpBexhiMng.update(entpBexhi);
			AuditLog audit = new AuditLog();
			audit.setAuditGroup("B");
			audit.setAuditId(entpBexhi.getId());
			audit.setAuditTitle("已提交大型展项目预约");
			audit.setAuditSendId("20");
			audit.setAuditTime(new Date());
			if (null != getEntpUser())
				audit.setAuditName(getEntpUser().getMc());
			audit.setAuditStatus("20");
			auditLogMng.save(audit);

			log("预约审核", " 已提交场馆预约申请", entpBexhi.getId(), null);
		}
		XMsg msg = new XMsg();
		msg.setState(true);
		return toJson(msg);
	}

	// 明细数据
	@RequestMapping(PATH_BOOK_DETAIL)
	public void bookDetail(@RequestParam("code") String code,
			@ModelAttribute("entpBexhi") EntpBexhi entpBexhi, ModelMap model) {
		model.addAttribute("code", code);
		if (null != getEntpUser()) {
			model.addAttribute("zid", getEntpUser().getUid());
			model.addAttribute("entpName", getEntpUser().getMc());		
		}	
		showBexhiView(entpBexhi, model);
		ExhiCfg cfg = getCfg();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		model.addAttribute("zbs",
				entpMng.findByProperty("userType", "Z", "createTime"));
		model.addAttribute("cbs",
				entpMng.findByProperty("userType", "C", "createTime"));
		model.addAttribute("bdate",
				df.format(DateUtil.addDate(new Date(), cfg.getBt().intValue())));
	}

	public String getBookUrl(String href, String status) {
		String url = "";
		// #01#03#05#10#15#20#25#30#50#60#90

		if ("01".equalsIgnoreCase(code)) {
			url += "<a href='book-view.jspx?code=01&infoId=" + href
					+ "' >【展会详情】</a>";

			if ("#01#03#".indexOf(status) > 0)
				url += "<a href='book-detail.jspx?code=01&infoId=" + href
						+ "' >【修改】</a>";
			if ("#10#".indexOf(status) > 0)
				url += "<a href='book-big-detail.jspx?code=01&infoId=" + href
						+ "' >【项目预约】</a>";

			if ("#30#40#50#60#".indexOf(status) > 0)
				url += "<a target='_blank' href='print-corp-exhi.jspx?code="
						+ code + "&infoId=" + href + "' >【打印材料】</a>";

			if ("#15#".indexOf(status) > 0)
				url += "<a href='book-big-detail.jspx?code=01&infoId=" + href
						+ "' >【修改】</a>";

			if ("#60#70#".indexOf(status) > 0)
				url += "<a href='tp-detail.jspx?infoId=" + href
						+ "'  >【台批】</a>";
		}

		if ("05".equalsIgnoreCase(code)) {
			if ("#05#".indexOf(status) > 0) {
				url += "<a href='book-check.jspx?code=05&infoId=" + href
						+ "' >【场馆确认】</a>";
			} else {
				url += "<a href='book-view.jspx?code=05&infoId=" + href
						+ "' >【展会详情】</a>";
			}
		}

		if ("60".equalsIgnoreCase(code)) {
			if ("#60#".indexOf(status) > 0) {
				url += "<a href='book-check.jspx?code=60&infoId=" + href
						+ "' >【合同确认】</a>";
			} else {
				url += "<a href='book-view.jspx?code=60&infoId=" + href
						+ "' >【展会详情】</a>";
			}
		}

		return url;
	}

	// 明细数据
	@RequestMapping(PATH_CHECK)
	public void infoCheck(@RequestParam("code") String code,
			@ModelAttribute("entpBexhi") EntpBexhi entpBexhi, ModelMap model) {
		model.addAttribute("code", code);
		showBexhiView(entpBexhi, model);
	}

	@RequestMapping(PATH_CHECK_SAVE)
	public String saveCheckInfo(@RequestParam("code") String code,
			@RequestParam("newStatus") String status,
			@RequestParam("auditName") String auditName,
			@RequestParam("auditRemark") String auditRemark,
			@ModelAttribute("entpBexhi") EntpBexhi entpBexhi, ModelMap model) {
		if (!entpBexhi.getStatus().equalsIgnoreCase(status)) {
			entpBexhi.setStatus(status);
			entpBexhiMng.update(entpBexhi);
			AuditLog audit = new AuditLog();
			audit.setAuditGroup("B");
			audit.setAuditId(entpBexhi.getId());
			audit.setAuditTitle("反馈预约确认信息");
			audit.setAuditSendId(status);
			audit.setAuditTime(new Date());
			if (null != getEntpUser())
				audit.setAuditName(getEntpUser().getMc() + " 确认人" + auditName);
			else
				audit.setAuditName(" 确认人" + auditName);
			audit.setAuditRemark(auditRemark);
			audit.setAuditStatus(status);
			auditLogMng.save(audit);
			log("预约审核", " 场馆预约通过", entpBexhi.getId(), null);
		}
		return "redirect:" + PATH_TABLE.substring(1) + ".jspx?code=05";
	}

	// 数据保存
	@RequestMapping(PATH_BIG_SAVE)
	public String saveInfo(HttpServletRequest request,
			@RequestParam("code") String code,
			@ModelAttribute("entpBexhi") EntpBexhi entpBexhiInfo, ModelMap model)
			throws IllegalStateException, IOException {
		entpBexhiInfo.setCreatetime(new Date());
		entpBexhiMng.save(entpBexhiInfo);
		XMsg msg = new XMsg();
		String entpId = entpBexhiInfo.getId();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

		if (saveUpload(multipartRequest, "attach1")) {
			attachMng.saveFileAttach(entpId, "YHCKZM");// 银行存款证明
		} else {
			msg.setState(false);
			msg.setMsg(attachMng.getErrors());
		}
		if (saveUpload(multipartRequest, "attach2")) {

			attachMng.saveFileAttach(entpId, "SNDZCZM");// 上年度资产证明（审计）
		} else {
			msg.setState(false);
			msg.setMsg(attachMng.getErrors());
		}
		if (saveUpload(multipartRequest, "attach3")) {
			attachMng.saveFileAttach(entpId, "XGBMYJ");// 相关部门意见
		} else {
			msg.setState(false);
			msg.setMsg(attachMng.getErrors());
		}

		if (entpBexhiInfo.getSbxh() == null) {
			String sql = "update t_entp_bexhi set sbxh=seq('"
					+ entpBexhiInfo.getYear() + "','apply') where  gid='"
					+ entpBexhiInfo.getId() + "'";
			entpBexhiMng.query(sql);
		}
		msg.setState(true);
		log("预约审核", "项目审核预约", entpBexhiInfo.getId(), null);
		return "redirect:" + PATH_BIG_VIEW.substring(1) + ".jspx?code=" + code
				+ "&infoId=" + entpBexhiInfo.getId();
	}

	// 明细数据
	@RequestMapping(PATH_BIG_VIEW)
	public void bigView(@RequestParam("code") String code,
			@ModelAttribute("entpBexhi") EntpBexhi entpBexhi, ModelMap model) {
		model.addAttribute("code", code);
		showBexhiView(entpBexhi, model);
	}

	@RequestMapping(PATH_BIG_SB)
	@ResponseBody
	public String BigSB(@ModelAttribute("entpBexhi") EntpBexhi entpBexhi,
			ModelMap model) {
		if ("10".equalsIgnoreCase(entpBexhi.getStatus())) {
			entpBexhi.setStatus("20"); // 申报到场馆确认
			entpBexhiMng.update(entpBexhi);
			log(entpBexhi.getId(), "已提交项目预约申请");
		}
		XMsg msg = new XMsg();
		msg.setState(true);
		return toJson(msg);
	}

	@RequestMapping(PATH_DELETE)
	@ResponseBody
	public String infoDelete(
			@RequestParam(value = "ids", required = true, defaultValue = "") String ids,
			@RequestParam("code") String code) {

		delete("t_entp_bexhi", "gid", ids);
		XMsg msg = new XMsg();
		msg.setState(true);
		return toJson(msg);
	}

	@ModelAttribute("entpBexhi")
	public EntpBexhi getEntpexhiInfo(
			@RequestParam(value = "infoId", required = true, defaultValue = "") String id) {
		EntpBexhi entpBexhi = entpBexhiMng.get(id);
		if (null == entpBexhi) {
			entpBexhi = new EntpBexhi();
		}
		return entpBexhi;
	}

	@Autowired
	@Qualifier("entpBexhiMng")
	private EntpBexhiMng entpBexhiMng;

}
